<template>
  <a-layout>
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
    >
      <p>
        <a-space type="small">
          <a-input-search
              v-model:value="searchName"
              placeholder="请输入名称"
              enter-button="搜索"
              size="large"
              style="width: 400px"
              allow-clear
              @search="handleSearch"
          />
          <a-button type="primary" @click="add()" size="large">
            新增
          </a-button>
        </a-space>
      </p>
      <a-table :columns="columns"
               :row-key="record => record.id"
               :data-source="ebooks"
               :pagination="pagination"
               :loading="loading"
               @change="handleTableChange"
      >
        <template #cover="{ text:cover }">
          <img v-if="cover" :src="cover" alt="avatar"/>
        </template>
        <template v-slot:category="{ text:record }">
          <span>{{ getCategoryName(record.category1Id) }}/{{ getCategoryName(record.category2Id) }}</span>
        </template>
        <template v-slot:action="{text,record}">
          <a-space type="small">
            <router-link :to="'/admin/doc?ebookId=' + record.id">
              <a-button type="primary">
                文档管理
              </a-button>
            </router-link>
            <a-button type="primary" @click="edite(record)">
              编辑
            </a-button>
            <a-button type="danger" @click="deleteById(record.id)">
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>

  <a-modal
      title="用户表单"
      v-model:visible="modalVisible"
      :confirm-loading="modalLoading"
      @ok="modalHandleOk"
  >
    <a-form :model="ebook" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="封面">
        <a-input v-model:value="ebook.cover"/>
      </a-form-item>
      <a-form-item label="名称">
        <a-input v-model:value="ebook.name"/>
      </a-form-item>
      <a-form-item label="分类">
        <a-cascader
            v-model:value="categoryIds"
            :field-names="{ label: 'name', value: 'id', children: 'children' }"
            :options="categoryTree"/>
      </a-form-item>
      <a-form-item label="描述">
        <a-input v-model:value="ebook.description" type="textarea"/>
      </a-form-item>
    </a-form>
  </a-modal>

</template>

<script lang="ts">
import {createVNode, defineComponent, onMounted, ref} from 'vue';
import axios from 'axios';
import {Tool} from "@/utils/tool";
import {Modal} from "ant-design-vue";
import {ExclamationCircleOutlined} from "@ant-design/icons-vue";


export default defineComponent({
  name: 'AdminEbook',
  setup() {

    const ebooks = ref();
    const pagination = ref({
      current: 1,
      pageSize: 8,
      total: 0
    });
    const loading = ref(false);

    const columns = [
      {
        title: '封面',
        dataIndex: 'cover',
        slots: {customRender: 'cover'}
      },
      {
        title: '名称',
        dataIndex: 'name'
      },
      {
        title: '分类',
        slots: {customRender: 'category'}
      },
      {
        title: '文档数',
        dataIndex: 'docCount'
      },
      {
        title: '阅读数',
        dataIndex: 'viewCount'
      },
      {
        title: '点赞数',
        dataIndex: 'voteCount'
      },
      {
        title: '操作',
        key: 'action',
        slots: {customRender: 'action'}
      }
    ];

    // 模态框
    const modalVisible = ref<boolean>(false);
    const modalLoading = ref<boolean>(false);

    // 表单
    // 数组类型[100,200] 对应一级分类和二级分类
    const categoryIds = ref();
    const ebook = ref();

    // 分类
    const categoryTree = ref();
    let categorys: any;
    /**
     * 数据查询
     **/
    const handleCategoryQuery = (params: any) => {
      loading.value = true;
      axios.get("/category/all", {
        params: params
      }).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          categorys = data.content;
          categoryTree.value = [];
          categoryTree.value = Tool.array2Tree(categorys, 0);
          handleQuery({
            page: 1,
            size: pagination.value.pageSize
          });
        }

      });
    };

    // 搜索
    const searchName = ref();

    /**
     * 修改
     * @param record
     */
    const edite = (record: any) => {
      modalVisible.value = true;
      ebook.value = record;
      categoryIds.value = [ebook.value.category1Id, ebook.value.category2Id];
    };
    /**
     * 删除
     * @param record
     */
    const deleteById = (record: any) => {
      Modal.confirm({
        title: () => '你确定要选择删除以下文档吗？',
        icon: () => createVNode(ExclamationCircleOutlined),
        content: () => '被删除后文档将无法恢复',
        onOk() {
          axios.delete("/ebook/delete", {
            params: {
              id: record
            }
          }).then((response) => {
            const data = response.data;
            if (data.success) {
              handleQuery({
                page: pagination.value.current,
                size: pagination.value.pageSize
              });
            }
          });
        },
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        onCancel() {},
      });
    };

    /**
     * 新增
     * @param record
     */
    const add = () => {
      modalVisible.value = true;
      ebook.value = {};
    };

    /**
     * 搜索框查询
     */
    const handleSearch = () => {
      handleQuery({
        page: 1,
        size: pagination.value.pageSize,
        name: searchName.value
      });
    }

    const modalHandleOk = () => {
      modalLoading.value = true;
      ebook.value.category1Id = categoryIds.value[0];
      ebook.value.category2Id = categoryIds.value[1];

      axios.post("/ebook/save", ebook.value).then((response) => {
        const data = response.data;
        console.log(categoryIds.value);
        if (data.success) {
          modalVisible.value = false;
          modalLoading.value = false;

          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize
          });
        }

      });

    }

    /**
     * 数据查询
     **/
    const handleQuery = (params: any) => {
      loading.value = true;
      // 如果不清空现有数据，则编辑保存重新加载数据后，再点编辑，则列表显示的还是编辑前的数据
      ebooks.value = [];
      axios.get("/ebook/list", {
        params: params
      }).then((response) => {
        loading.value = false;
        const data = response.data;
        ebooks.value = data.content.list;

        // 重置分页参数
        pagination.value.current = params.page;
        pagination.value.total = data.content.total;
      });
    };

    /**
     * 表格点击页码时触发
     */
    const handleTableChange = (pagination: any) => {
      handleQuery({
        page: pagination.current,
        size: pagination.pageSize,
        name: searchName.value
      });
    };


    onMounted(() => {
      handleCategoryQuery({});
    });

    const getCategoryName = (id: any) => {
      let result = "";
      categorys.forEach((item: any) => {
        if (item.id === id) {
          result = item.name;
        }
      });
      return result;
    };


    return {
      ebooks,
      pagination,
      columns,
      loading,
      handleTableChange,
      getCategoryName,
      //模态框
      modalVisible,
      modalLoading,
      edite,
      deleteById,
      modalHandleOk,
      //表单
      ebook,
      add,
      categoryTree,
      categoryIds,
      // 搜索
      handleSearch,
      searchName,
    }
  }
});
</script>

<style scoped>
img {
  width: 50px;
  height: 50px;
}
</style>
